

#define LOG_TAG "GlTest"

#include <stdint.h>
#include <sys/types.h>
#include <math.h>
#include <fcntl.h>
#include <utils/misc.h>
#include <signal.h>

#include <cutils/properties.h>

#include <androidfw/AssetManager.h>
#include <binder/IPCThreadState.h>
#include <utils/Atomic.h>
#include <utils/Errors.h>
#include <utils/Log.h>
#include <utils/threads.h>

#include <ui/PixelFormat.h>
#include <ui/Rect.h>
#include <ui/Region.h>
#include <ui/DisplayInfo.h>
#include <ui/FramebufferNativeWindow.h>

#include <gui/ISurfaceComposer.h>
#include <gui/Surface.h>
#include <gui/SurfaceComposerClient.h>

#include <core/SkBitmap.h>
#include <core/SkStream.h>
#include <core/SkImageDecoder.h>

#include <GLES/gl.h>
#include <GLES/glext.h>
#include <EGL/eglext.h>

#include "GlTest.h"


#define EXIT_PROP_NAME "service.bootanim.exit"

namespace android {

    GlTest::GlTest(sp<FrameQueue> q) : Thread(false)
    {
        mSession = new SurfaceComposerClient();

        mQueue = q;
    }

    GlTest::~GlTest() {
    }

    void GlTest::onFirstRef() {
        status_t err = mSession->linkToComposerDeath(this);
        ALOGE_IF(err, "linkToComposerDeath failed (%s) ", strerror(-err));
        if (err == NO_ERROR) {
            run("GlTest", PRIORITY_DISPLAY);
        }
    }

    sp<SurfaceComposerClient> GlTest::session() const {
        return mSession;
    }


    void GlTest::binderDied(const wp<IBinder>&)
    {
        // woah, surfaceflinger died!
        ALOGD("SurfaceFlinger died, exiting...");

        // calling requestExit() is not enough here because the Surface code
        // might be blocked on a condition variable that will never be updated.
        kill( getpid(), SIGKILL );
        requestExit();
    }

    status_t GlTest::readyToRun() {
        mAssets.addDefaultAssets();

        sp<IBinder> dtoken(SurfaceComposerClient::getBuiltInDisplay(
                               ISurfaceComposer::eDisplayIdMain));
        DisplayInfo dinfo;
        status_t status = SurfaceComposerClient::getDisplayInfo(dtoken, &dinfo);
        if (status)
            return -1;

        // create the native surface
        sp<SurfaceControl> control = session()->createSurface(String8("GlTest"),
                                                              dinfo.w, dinfo.h, PIXEL_FORMAT_RGB_565);

        SurfaceComposerClient::openGlobalTransaction();
        control->setLayer(0x40000000);
        SurfaceComposerClient::closeGlobalTransaction();

        sp<Surface> s = control->getSurface();

        // initialize opengl and egl
        const EGLint attribs[] = {
            EGL_RED_SIZE,   8,
            EGL_GREEN_SIZE, 8,
            EGL_BLUE_SIZE,  8,
            EGL_DEPTH_SIZE, 0,
            EGL_NONE
        };
        EGLint w, h, dummy;
        EGLint numConfigs;
        EGLConfig config;
        EGLSurface surface;
        EGLContext context;

        EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

        eglInitialize(display, 0, 0);
        eglChooseConfig(display, attribs, &config, 1, &numConfigs);
        surface = eglCreateWindowSurface(display, config, s.get(), NULL);
        context = eglCreateContext(display, config, NULL, NULL);
        eglQuerySurface(display, surface, EGL_WIDTH, &w);
        eglQuerySurface(display, surface, EGL_HEIGHT, &h);

        if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
            return NO_INIT;

        mDisplay = display;
        mContext = context;
        mSurface = surface;
        mWidth = w;
        mHeight = h;
        mFlingerSurfaceControl = control;
        mFlingerSurface = s;

        return NO_ERROR;
    }

    status_t GlTest::initTexture(Texture* texture, AssetManager& assets, const char* path) {

        SkBitmap bitmap;
        SkImageDecoder::DecodeFile(path, &bitmap,
                    SkBitmap::kNo_Config,
                    SkImageDecoder::kDecodePixels_Mode);

        // ensure we can call getPixels(). No need to call unlock, since the
        // bitmap will go out of scope when we return from this method.
        bitmap.lockPixels();

        const int w = bitmap.width();
        const int h = bitmap.height();
        const void* p = bitmap.getPixels();

        GLint crop[4] = { 0, h, w, -h };
        texture->w = w;
        texture->h = h;

        glGenTextures(1, &texture->name);
        glBindTexture(GL_TEXTURE_2D, texture->name);

        switch (bitmap.getConfig()) {
        case SkBitmap::kA8_Config:
            glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_ALPHA,
                         GL_UNSIGNED_BYTE, p);
            break;
        case SkBitmap::kARGB_4444_Config:
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
                         GL_UNSIGNED_SHORT_4_4_4_4, p);
            break;
        case SkBitmap::kARGB_8888_Config:
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
                         GL_UNSIGNED_BYTE, p);
            break;
        case SkBitmap::kRGB_565_Config:
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,
                         GL_UNSIGNED_SHORT_5_6_5, p);
            break;
        default:
            break;
        }

        glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        return NO_ERROR;
    }

    status_t GlTest::initTexture(Texture* texture, const void* buffer, size_t len)
    {
    #if 1
        SkBitmap bitmap;
        SkMemoryStream  stream(buffer, len);
        ALOGD("%s: stream format: %s", __func__, SkImageDecoder::GetFormatName(SkImageDecoder::GetStreamFormat(&stream)));

        SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
        if (NULL == codec) {
            ALOGE("%s: fail to find a appropriate decoder.", __func__);
            return BAD_VALUE;
        }
        if (codec) {
            codec->setDitherImage(false);

            codec->decode(&stream, &bitmap,
                    //SkBitmap::kARGB_8888_Config,
                    SkBitmap::kNo_Config,
                    SkImageDecoder::kDecodePixels_Mode);
            delete codec;
        }
    #else
        bool ret;
        SkBitmap bitmap;
        SkImageDecoder::DecodeMemory(buffer, len,
            &bitmap, SkBitmap::kNo_Config, SkImageDecoder::kDecodePixels_Mode, &SkImageDecoder::Format::kBMP_Format);
        if (false == ret) {
            ALOGE("%s: fail to decode", __func__);
            return BAD_VALUE;
        }
    #endif

        // ensure we can call getPixels(). No need to call unlock, since the
        // bitmap will go out of scope when we return from this method.
        bitmap.lockPixels();
    
        const int w = bitmap.width();
        const int h = bitmap.height();
        const void* p = bitmap.getPixels();
        ALOGD("%s: w=%d, h=%d, p=%p", __func__, w, h, p);
    
        GLint crop[4] = { 0, h, w, -h };
        int tw = 1 << (31 - __builtin_clz(w));
        int th = 1 << (31 - __builtin_clz(h));
        if (tw < w) tw <<= 1;
        if (th < h) th <<= 1;

        texture->w = w;
        texture->h = h;

//        glGenTextures(1, &texture->name);
        glBindTexture(GL_TEXTURE_2D, texture->name);

        switch (bitmap.getConfig()) {
            case SkBitmap::kARGB_8888_Config:
                ALOGD("%s L%d", __func__, __LINE__);
                if (tw != w || th != h) {
                    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
                            GL_UNSIGNED_BYTE, 0);
                    glTexSubImage2D(GL_TEXTURE_2D, 0,
                            0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, p);
                } else {
                    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA,
                            GL_UNSIGNED_BYTE, p);
                }
                break;
    
            case SkBitmap::kRGB_565_Config:
                ALOGD("%s L%d", __func__, __LINE__);
                if (tw != w || th != h) {
                    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
                            GL_UNSIGNED_SHORT_5_6_5, 0);
                    glTexSubImage2D(GL_TEXTURE_2D, 0,
                            0, 0, w, h, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, p);
                } else {
                    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_RGB,
                            GL_UNSIGNED_SHORT_5_6_5, p);
                }
                break;
            default:
                ALOGD("%s L%d", __func__, __LINE__);
                break;
        }
    
        glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
    
        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

        return NO_ERROR;
    }

    bool GlTest::showFrame()
    {
        // clear screen
        glShadeModel(GL_FLAT);
        glDisable(GL_DITHER);
        glDisable(GL_SCISSOR_TEST);
        glClearColor(0,0,0,1);
        glClear(GL_COLOR_BUFFER_BIT);
        eglSwapBuffers(mDisplay, mSurface);

        glEnable(GL_TEXTURE_2D);
        glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

        // !!! to avoid be killed, must be outside the loop !!!
        // https://www.cnblogs.com/vernon/articles/1885223.html
        glGenTextures(1, &(mAndroid[0].name));


        do {
            void* frame = NULL;
            int idx = -1;
            int len = mQueue->getFrameSize() / 4 * 3 + 54;  // bmp file size

            mQueue->acquireBuffer(&idx, &frame);
            //ALOGD("%s: acquireBuffer id=%d, frame=%p, len=%d", __func__, idx, frame, len);
            if (idx < 0 || frame == NULL) {
                continue;
            }

            initTexture(&mAndroid[0], frame, len);

            mQueue->releaseBuffer(idx);

            const GLint xc = (mWidth  - mAndroid[0].w) / 2;
            const GLint yc = (mHeight - mAndroid[0].h) / 2;
            const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);
    
            glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
                      updateRect.height());
    
            // Blend state
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    
            const nsecs_t startTime = systemTime();

            nsecs_t now = systemTime();
            double time = now - startTime;
//            float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
//            GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
//            GLint x = xc - offset;

            glDisable(GL_SCISSOR_TEST);
            glClear(GL_COLOR_BUFFER_BIT);

            glEnable(GL_SCISSOR_TEST);
//            glDisable(GL_BLEND);
//            glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
//            glDrawTexiOES(x,                 yc, 0, mAndroid[1].w, mAndroid[1].h);
//            glDrawTexiOES(x + mAndroid[1].w, yc, 0, mAndroid[1].w, mAndroid[1].h);

            glEnable(GL_BLEND);
            glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
            glDrawTexiOES(xc, yc, 0, mAndroid[0].w, mAndroid[0].h);

            EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
            if (res == EGL_FALSE)
                break;

            // 12fps: don't animate too fast to preserve CPU
            const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
            if (sleepTime > 0)
                usleep(sleepTime);

            checkExit();
        } while (!exitPending());

        glDeleteTextures(1, &mAndroid[0].name);
//        glDeleteTextures(1, &mAndroid[1].name);
        return false;
    }

    bool GlTest::showPicture()
    {
        initTexture(&mAndroid[0], mAssets, "/data/tux.jpg");
//        initTexture(&mAndroid[1], mAssets, "/data/tux.jpg");

        // clear screen
        glShadeModel(GL_FLAT);
        glDisable(GL_DITHER);
        glDisable(GL_SCISSOR_TEST);
        glClearColor(0,0,0,1);
        glClear(GL_COLOR_BUFFER_BIT);
        eglSwapBuffers(mDisplay, mSurface);

        glEnable(GL_TEXTURE_2D);
        glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

        const GLint xc = (mWidth  - mAndroid[0].w) / 2;
        const GLint yc = (mHeight - mAndroid[0].h) / 2;
        const Rect updateRect(xc, yc, xc + mAndroid[0].w, yc + mAndroid[0].h);

        glScissor(updateRect.left, mHeight - updateRect.bottom, updateRect.width(),
                  updateRect.height());

        // Blend state
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

        const nsecs_t startTime = systemTime();
        do {
            nsecs_t now = systemTime();
            double time = now - startTime;
//            float t = 4.0f * float(time / us2ns(16667)) / mAndroid[1].w;
//            GLint offset = (1 - (t - floorf(t))) * mAndroid[1].w;
//            GLint x = xc - offset;

            glDisable(GL_SCISSOR_TEST);
            glClear(GL_COLOR_BUFFER_BIT);

            glEnable(GL_SCISSOR_TEST);
//            glDisable(GL_BLEND);
//            glBindTexture(GL_TEXTURE_2D, mAndroid[1].name);
//            glDrawTexiOES(x,                 yc, 0, mAndroid[1].w, mAndroid[1].h);
//            glDrawTexiOES(x + mAndroid[1].w, yc, 0, mAndroid[1].w, mAndroid[1].h);

            glEnable(GL_BLEND);
            glBindTexture(GL_TEXTURE_2D, mAndroid[0].name);
            glDrawTexiOES(xc, yc, 0, mAndroid[0].w, mAndroid[0].h);

            EGLBoolean res = eglSwapBuffers(mDisplay, mSurface);
            if (res == EGL_FALSE)
                break;

            // 12fps: don't animate too fast to preserve CPU
            const nsecs_t sleepTime = 83333 - ns2us(systemTime() - now);
            if (sleepTime > 0)
                usleep(sleepTime);

            checkExit();
        } while (!exitPending());

        glDeleteTextures(1, &mAndroid[0].name);
//        glDeleteTextures(1, &mAndroid[1].name);
        return false;
    }

    void GlTest::checkExit() {
        // Allow surface flinger to gracefully request shutdown
        char value[PROPERTY_VALUE_MAX];
        property_get(EXIT_PROP_NAME, value, "0");
        int exitnow = atoi(value);
        if (exitnow) {
            requestExit();
        }
    }

    bool GlTest::threadLoop()
    {
        bool r = false;

        // do show ...
//        r = showPicture();
        r = showFrame();

        // No need to force exit anymore
        property_set(EXIT_PROP_NAME, "0");

        // do sth clear
        eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
        eglDestroyContext(mDisplay, mContext);
        eglDestroySurface(mDisplay, mSurface);
        mFlingerSurface.clear();
        mFlingerSurfaceControl.clear();
        eglTerminate(mDisplay);
        IPCThreadState::self()->stopProcess();
        return r;
    }

}
